package com.scott.api.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.TimeUnit;

/**
 * Curator 事件
 *
 * @author Scott 2017/11/2 16:25
 */
public class CuratorEventDemo {
    /**
     * curator 提供了三种watcher来做节点的监听
     * 1: PathCache 监视一个路径下的子节点的创建、删除、节点数据跟新
     * 2: NodeCache 监视一个节点的创建、更新、删除 缓存节点数据
     * 3: TreeCache PathCache+NodeCache的合体 监视路径下的创建，并缓存路径下的所有子节点的数据
     */
    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFramework = CuratorClientUtils.getInstance();

        //节点变化 nodeCache
        /*NodeCache nodeCache = new NodeCache(curatorFramework, "/curator", false);
        nodeCache.start(true);
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("节点数据发生变化,变化的结果：" + new String(nodeCache.getCurrentData().getData()));
            }
        });

        curatorFramework.setData().forPath("/curator", "花花".getBytes());
        System.in.read();*/

        //PatchChildrenCache
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, "/curator", false);
        //NORMAL BUILD_INITIAL_CACHE POST_INITIALIZED_EVENT
        pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                    case CHILD_ADDED:
                        System.out.println("增加节点");
                        break;
                    case CHILD_REMOVED:
                        System.out.println("删除节点");
                        break;
                    case CHILD_UPDATED:
                        System.out.println("更新节点");
                        break;
                    default:
                        break;
                }
            }
        });


        curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath("/curator/event", "event".getBytes());
        TimeUnit.SECONDS.sleep(1);

        curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath("/curator/event/event1", "event1 ".getBytes());
        TimeUnit.SECONDS.sleep(1);

        curatorFramework.setData().forPath("/curator/event", "222".getBytes());
        TimeUnit.SECONDS.sleep(1);

        curatorFramework.delete().forPath("/curator/event/event1");

        System.in.read();

    }
}
